#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
彩票助手主应用程序
功能：爬取历史彩票数据，预测下期号码，提供Web界面
"""

from flask import Flask, render_template, jsonify, request
from flask_cors import CORS
import os
import sys
from datetime import datetime

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# 导入自定义模块
from modules.crawler import LotteryCrawler
from modules.predictor import LotteryPredictor
from modules.database import DatabaseManager
from modules.visualizer import DataVisualizer

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 初始化组件
db_manager = DatabaseManager()
crawler = LotteryCrawler(db_manager)
predictor = LotteryPredictor()
visualizer = DataVisualizer()

@app.route('/')
def index():
    """主页"""
    return render_template('index.html')

@app.route('/api/history')
def get_history():
    """获取历史开奖数据"""
    try:
        lottery_type = request.args.get('type', 'qxc')
        limit = int(request.args.get('limit', 10000))
        data = db_manager.get_recent_data(lottery_type, limit)
        return jsonify({
            'success': True,
            'data': data,
            'lottery_type': lottery_type
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        })

@app.route('/api/predict')
def predict_numbers():
    """预测下期号码"""
    try:
        lottery_type = request.args.get('type', 'qxc')
        method = request.args.get('method', 'ensemble')
        prediction = predictor.predict_next_numbers(lottery_type, method)
        return jsonify({
            'success': True,
            'prediction': prediction,
            'timestamp': datetime.now().isoformat()
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        })

@app.route('/api/batch_predict', methods=['POST'])
def batch_predict_numbers():
    """批量预测 - 支持多种算法同时预测"""
    try:
        data = request.get_json()
        lottery_type = data.get('type', 'qxc')
        methods = data.get('methods', ['ensemble'])
        count = data.get('count', 1)  # 每种算法预测的组数
        
        if not isinstance(methods, list) or len(methods) == 0:
            return jsonify({
                'success': False,
                'error': '请至少选择一种预测方法'
            })
        
        # 验证预测方法
        valid_methods = ['ensemble', 'frequency', 'pattern', 'ml', 'hot_cold', 'position', 'min_frequency']
        invalid_methods = [m for m in methods if m not in valid_methods]
        if invalid_methods:
            return jsonify({
                'success': False,
                'error': f'不支持的预测方法: {", ".join(invalid_methods)}'
            })
        
        batch_results = []
        
        # 为每种方法生成指定数量的预测
        for method in methods:
            method_results = []
            for i in range(count):
                prediction = predictor.predict_next_numbers(lottery_type, method)
                if prediction:
                    method_results.append({
                        'index': i + 1,
                        'prediction': prediction
                    })
            
            batch_results.append({
                'method': method,
                'method_name': get_method_name(method),
                'results': method_results
            })
        
        return jsonify({
            'success': True,
            'batch_results': batch_results,
            'total_predictions': sum(len(result['results']) for result in batch_results),
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        })

def get_method_name(method):
    """获取预测方法的中文名称"""
    method_names = {
        'ensemble': '集成算法',
        'frequency': '频率分析',
        'pattern': '模式分析',
        'ml': '机器学习',
        'hot_cold': '冷热号分析',
        'position': '位置分析',
        'min_frequency': '最低频率分析'
    }
    return method_names.get(method, method)

@app.route('/api/crawl', methods=['GET', 'POST'])
def crawl_data():
    """手动触发数据爬取"""
    try:
        if request.method == 'POST':
            data = request.get_json() or {}
            lottery_type = data.get('lottery_type', 'qxc')
            max_periods = int(data.get('max_periods', 100))
            force_update = data.get('force_update', False)
        else:
            lottery_type = request.args.get('type', 'qxc')
            max_periods = int(request.args.get('periods', 10))
            force_update = request.args.get('force_update', 'false').lower() == 'true'
        
        if force_update:
            # 强制更新最近几期数据
            success_count = crawler.force_update_recent_data(max_periods)
            message = f'强制更新了 {success_count} 条七星彩数据'
        else:
            # 只爬取新数据
            success_count = crawler.crawl_latest_data(max_periods)
            if success_count == 0:
                message = '数据库已是最新，无新数据可爬取。如需强制更新，请使用force_update参数'
            else:
                message = f'成功爬取 {success_count} 条七星彩数据'
        
        return jsonify({
            'success': True,
            'message': message,
            'lottery_type': lottery_type,
            'count': success_count
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        })

@app.route('/api/statistics')
def get_statistics():
    """获取统计数据"""
    try:
        lottery_type = request.args.get('type', 'qxc')
        stats = visualizer.generate_statistics(lottery_type)
        return jsonify({
            'success': True,
            'statistics': stats,
            'lottery_type': lottery_type
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        })

if __name__ == '__main__':
    # 初始化数据库
    db_manager.init_database()
    
    # 启动应用
    print("彩票助手应用启动中...")
    print("访问地址: http://localhost:5000")
    app.run(debug=True, host='0.0.0.0', port=5000)